%% Author: vivimice
%% Created: Feb 21, 2012
%% Description: TODO: Add description to code_gen
-module(code_gen).

%%
%% Include files
%%

%%
%% Exported Functions
%%
-export([generate_server_code/1]).

%%
%% API Functions
%%
generate_server_code([]) ->
	ok;
generate_server_code([Head|Rest]) ->
	generate_server_exports([Head|Rest]),
	generate_server_state([Head|Rest]),
	generate_server_getter_setter([Head|Rest]),
	generate_server_handlers([Head|Rest]).

generate_server_exports([]) ->
	io:nl();
generate_server_exports([Head|Rest]) ->
	Name = atom_to_list(Head),
	io:format("-export([get_~s/1, set_~s/2]).\n", [Name, Name]),
	generate_server_exports(Rest).

generate_server_state(List) ->
	generate_server_state(List, []).

generate_server_state([], Acc) ->
	io:format("-record(state, {~s}).\n", [string:join(Acc, ", ")]),
	io:nl();
generate_server_state([Head|Rest], Acc) ->
	generate_server_state(Rest, Acc ++ [atom_to_list(Head)]).

generate_server_getter_setter([]) ->
	ok;
generate_server_getter_setter([Head|Rest]) ->
	Name = atom_to_list(Head),
	io:format("get_~s(ServerRef) ->\n\t{~s, Value} = gen_server:call(ServerRef, get_~s),\n\tValue.\n", [Name, Name, Name]),
	io:nl(),
	io:format("set_~s(ServerRef, Value) ->\n\tok = gen_server:call(ServerRef, {set_~s, Value}).\n", [Name, Name]),
	io:nl(),
	generate_server_getter_setter(Rest).

generate_server_handlers([]) ->
	io:format("handle_call(_Other, _From, State) ->\n\t{reply, undef, State}.\n"),
	io:nl(),
	ok;
generate_server_handlers([Head|Rest]) ->
	Name = atom_to_list(Head),
	io:format("handle_call(get_~s, _From, State) ->\n\t{reply, {~s, State#state.~s}, State};\n", [Name, Name, Name]),
	io:nl(),
	io:format("handle_call({set_~s, Value}, _From, State) ->\n\t{reply, ok, State#state{~s = Value}};\n", [Name, Name]),
	io:nl(),
	generate_server_handlers(Rest).

%%
%% Local Functions
%%

